export function listToMap (arr, key) {
  const map = new Map()
  arr.forEach(item => {
    map.set(item[key], item)
  })
  return map
}

export function fillProperty (arr, options) {
  return arr.map(item => {
    return {
      ...item,
      ...options
    }
  })
}

export function replaceByProperty (arr, properties, newItem) {
  for (let i = 0, l = arr.length; i < l; i++) {
    const item = arr[i]
    let res = true
    const keys = Object.keys(properties)
    for (let j = 0, m = keys.length; j < m; j++) {
      const key = keys[j]
      if (properties[key] !== item[key]) {
        res = false
        break
      }
    }
    if (res) {
      arr.splice(i, 1, newItem)
      break
    }
  }
  return arr
}

export function getArrDifSameValue (arr1, arr2, primaryKey = 'id') {
  const result = []
  for (let i = 0; i < arr2.length; i++) {
    const obj = arr2[i]
    const id2 = obj[primaryKey]
    let isExist = false
    for (let j = 0; j < arr1.length; j++) {
      const aj = arr1[j]
      const id1 = aj[primaryKey]
      if (id1 === id2) {
        isExist = true
        break
      }
    }
    if (isExist) {
      result.push(obj)
    }
  }
  return result
}

// 返回arr2
export function getArrDifSameValueWithDiffKey (arr1, primaryKey1 = 'id', arr2, primaryKey2 = 'id') {
  const result = []
  for (let i = 0; i < arr2.length; i++) {
    const obj = arr2[i]
    const id2 = obj[primaryKey2]
    let isExist = false
    for (let j = 0; j < arr1.length; j++) {
      const aj = arr1[j]
      const id1 = aj[primaryKey1]
      if (id1 === id2) {
        isExist = true
        break
      }
    }
    if (isExist) {
      result.push(obj)
    }
  }
  return result
}
